//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package com.bootdo.clouddo.advice;

import com.alibaba.fastjson.JSON;
import com.bootdo.clouddo.annotation.Encrypt;
import com.bootdo.clouddo.config.SecretKeyConfig;
import com.bootdo.clouddo.utils.rsa.Base64Util;
import com.bootdo.clouddo.utils.rsa.RSAUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

@ControllerAdvice
public class EncryptResponseBodyAdvice implements ResponseBodyAdvice<Object> {
    private Logger log = LoggerFactory.getLogger(this.getClass());
    private boolean encrypt;
    @Autowired
    private SecretKeyConfig secretKeyConfig;

    private static ThreadLocal<Boolean> encryptLocal = new ThreadLocal();

    public EncryptResponseBodyAdvice() {
    }

    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        this.encrypt = false;
        if (returnType.getMethod().isAnnotationPresent(Encrypt.class) && !this.secretKeyConfig.isDebug()) {
            this.encrypt = true;
        }

        return this.encrypt;
    }

    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        Boolean status = (Boolean)encryptLocal.get();
        if (null != status && !status) {
            encryptLocal.remove();
            return body;
        } else {
            if (this.encrypt) {
                String publicKey = this.secretKeyConfig.getPublicKey();

                try {
                    String content = JSON.toJSONString(body);
                    if (!StringUtils.hasText(publicKey)) {
                        throw new NullPointerException("Please configure rsa.encrypt.privatekeyc parameter!");
                    }

                    byte[] data = content.getBytes();
                    byte[] encodedData = RSAUtil.encrypt(data, publicKey);
                    String result = Base64Util.encode(encodedData);
                    this.log.info("Pre-encrypted data：{}，After encryption：{}", content, result);
                    return result;
                } catch (Exception var13) {
                    this.log.error("Encrypted data exception", var13);
                }
            }

            return body;
        }
    }
}
